/**
 * 
 */
package com.google.code.sip.ucenter.dao;

import java.util.Set;

import org.bson.types.ObjectId;
import org.junit.BeforeClass;
import org.junit.Test;

import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.DBRef;

/**
 * @author Liuye
 * 
 */
public class UpgradeMongoData extends BaseMongoTest {
	@BeforeClass
	public static void beforeTest() throws Exception {
		init();
	}

	@Test
	public void upgrade() {
		DB db = mongoFactory.getMongo().getDB("ucenter");
		Set<String> collectionNames = db.getCollectionNames();
		for (String collectionName : collectionNames) {
			upgradeCollectionData(db.getCollection(collectionName));
		}
	}

	private void upgradeCollectionData(DBCollection dbCollection) {
		DBCursor cur = dbCollection.find();
		while (cur.hasNext()) {
			DBObject dbObject = cur.next();
			DBObject newDBObject = new BasicDBObject();
			for (String key : dbObject.keySet()) {
				Object newValue = getNewValue(dbObject.get(key));
				newDBObject.put(key, newValue);
			}
			dbCollection.update(dbObject, newDBObject, false, false);
		}
	}

	private Object getNewValue(Object value) {
		if (value instanceof ObjectId) {
			return ((ObjectId) value).toString();
		} else if (value instanceof DBRef) {
			DBRef dbref = new DBRef(null, ((DBRef) value).getRef(),
					((DBRef) value).getId().toString());
			return dbref;
		} else if (value instanceof BasicDBList) {
			BasicDBList dbList = (BasicDBList) value;
			BasicDBList newList = new BasicDBList();
			for (Object element : dbList) {
				newList.add(getNewValue(element));
			}
			return newList;
		} else if (value instanceof BasicDBObject) {
			BasicDBObject dbObject = (BasicDBObject) value;
			DBObject newDBObject = new BasicDBObject();
			for (String key : dbObject.keySet()) {
				Object newValue = getNewValue(dbObject.get(key));
				newDBObject.put(key, newValue);
			}
			return newDBObject;
		} else {
			return value;
		}
	}
}
